package com.asseco.mio.codex.controllers;

import com.asseco.mio.UserInstitution;
import com.asseco.mio.codex.Industry;
import com.asseco.mio.codex.Institution;
import com.asseco.mio.codex.UserInstitutionsForm;
import com.asseco.mio.core.webapp.controller.BaseFormController;
import com.asseco.persistence.service.HibernateUtil;
import org.appfuse.model.User;
import org.appfuse.service.UserManager;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.appfuse.service.GenericManager;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Qualifier;

/**
 * Implementation of <strong>SimpleFormController</strong> that interacts with
 * the {@link UserManager} to retrieve/persist values to the database.
 *
 * <p><a href="UserFormController.java.html"><i>View Source</i></a>
 *
 * @author <a href="mailto:matt@raibledesigns.com">Matt Raible</a>
 */
@Controller
@RequestMapping("/chooseindustry*")
public class ChooseIndustryController extends BaseFormController {

    private UserManager userManager = null;
    private GenericManager<Institution, String> institutionManager = null;
    private GenericManager<Industry, String> industryManager = null;
    private GenericManager<UserInstitution, String> userInstitutionManager = null;


    @Autowired
    public void setUserManager(UserManager userManager) {
        this.userManager = userManager;
    }

        @Autowired
    public void setIndustryManager(@Qualifier("industryManager") GenericManager<Industry, String> industryManager) {
        this.industryManager = industryManager;
    }

    @Autowired
    public void setInstitutionManager(@Qualifier("institutionManager") GenericManager<Institution, String> institutionManager) {
        this.institutionManager = institutionManager;
    }

    @Autowired
    public void setUserInstitutionManager(@Qualifier("userInstitutionManager") GenericManager<UserInstitution, String> userInstitutionManager) {
        this.userInstitutionManager = userInstitutionManager;
    }

    public ChooseIndustryController() {
        setCancelView("redirect:mainMenu");
        setSuccessView("redirect:userinstitutionsearch");
    }

    @ModelAttribute
    public UserInstitutionsForm userInstitutionsForm() {
        UserInstitutionsForm x = new UserInstitutionsForm(new User(), null,getAllActiveInstitutions(institutionManager.getAll()));
        return x;
    }

    @ModelAttribute
    @RequestMapping(method = RequestMethod.POST)
    public String onSubmit(UserInstitutionsForm userInstitutionsForm, BindingResult errors, HttpServletRequest request,
                           HttpServletResponse response)
            throws Exception {


        String success = getSuccessView();
        Locale locale = request.getLocale();
       // Institution inst = institutionManager.get(userInstitutionsForm.getInstitution().getId());
        Industry industry = industryManager.get(userInstitutionsForm.getIndustry().getId());


        User u = userManager.get(userInstitutionsForm.getUser().getId());

        Session session = HibernateUtil.getSessionFactory().openSession();
        session.beginTransaction();

        Criteria criteria  = session.createCriteria(UserInstitution.class).add(Restrictions.like("user", u));
        List result = criteria.list();
        session.getTransaction().commit();




      
       List institutions = getAllInstitutionsForIndustry(industry);
        if (result.isEmpty()){

            for (int i=0; i<institutions.size();i++){
            UserInstitution uInstitution = new UserInstitution();
            uInstitution.setUser(u);
            uInstitution.setInstitution((Institution) institutions.get(i));
            userInstitutionManager.save(uInstitution);
            }
            saveMessage(request, getText("userInstitution.DejnostaEDodadena", locale));

        }
        else {

            for (int i=0; i<result.size();i++){
            UserInstitution usrInst = (UserInstitution) result.get(i);
            userInstitutionManager.remove(usrInst.getId());
            }
            for (int i=0; i<institutions.size();i++){
            UserInstitution uInstitution = new UserInstitution();
            uInstitution.setUser(u);
            uInstitution.setInstitution((Institution) institutions.get(i));
            userInstitutionManager.save(uInstitution);
            }
            saveMessage(request, getText("userInstitution.DejnostaEDodadenaZaIzbraniotUser", locale));

        }

        return success;
    }

    @ModelAttribute
    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST})
    public UserInstitutionsForm showForm(HttpServletRequest request, HttpServletResponse response)
            throws Exception {

             long id = (long) Integer.parseInt(request.getParameter("id"));

        UserInstitutionsForm userInstitutionsForm = this.userInstitutionsForm();
        User tempUser = userManager.get(id);

        userInstitutionsForm.getUser().setFirstName(tempUser.getFirstName());
        userInstitutionsForm.getUser().setLastName(tempUser.getLastName());
        userInstitutionsForm.getUser().setUsername(tempUser.getUsername());
        userInstitutionsForm.getUser().setId(id);

        Session session = HibernateUtil.getSessionFactory().openSession();
        session.beginTransaction();
        Criteria criteria  = session.createCriteria(UserInstitution.class).add(Restrictions.like("user", tempUser));
        List result = criteria.list();
        session.getTransaction().commit();
       // userInstitutionsForm.setSelectedInstitutions(result);

        UserInstitutionsForm x = new UserInstitutionsForm(tempUser, industryManager.getAll(), result, getAllActiveInstitutions(institutionManager.getAll()));


        return x;
    }

    public List getAllActiveInstitutions(List<Institution> list) {

        List result = new ArrayList();
        for (int i = 0; i < list.size(); i++) {
            Institution ga = list.get(i);
            if (ga.getStatus() == true) {
                result.add(ga);
            }

        }

        return result;
    }

    public List getAllInstitutionsForIndustry(Industry industry){
        Session session = HibernateUtil.getSessionFactory().openSession();
         session.beginTransaction();
        Criteria criteria  = session.createCriteria(Institution.class).add(Restrictions.like("industry", industry));
        List result = criteria.list();
        session.getTransaction().commit();
        return result;
    }
}

